package com.hrzyit.whistle.im.ui.activity

import android.content.Intent
import android.graphics.drawable.AnimationDrawable
import android.media.MediaPlayer
import android.os.Bundle
import android.os.Handler
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.hrzyit.base.ui.activity.BaseActivity
import com.hrzyit.base.utils.DateUtils
import com.hrzyit.base.utils.MediaManager
import com.hrzyit.whistle.im.R
import com.hrzyit.whistle.im.common.IMConstants
import com.hrzyit.whistle.im.entity.FullImageInfo
import com.hrzyit.whistle.im.entity.MessageInfo
import com.hrzyit.whistle.im.ui.adapter.ChatAdapter
import com.hrzyit.whistle.im.ui.adapter.CommonFragmentPagerAdapter
import com.hrzyit.whistle.im.ui.fragment.ChatFunctionFragment
import com.hrzyit.whistle.im.widgets.EmotionInputDetector
import kotlinx.android.synthetic.main.activity_im_main.*
import kotlinx.android.synthetic.main.include_reply_layout.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 吹哨聊天群界面
 * @author YangWei
 * @date 2019/4/22
 */
@Route(path = "/im/main")
class ImMainActivity : BaseActivity() {

    private lateinit var fragments: MutableList<Fragment>

    private lateinit var viewPagerAdapter: CommonFragmentPagerAdapter

    private lateinit var mDetector: EmotionInputDetector

    private lateinit var chatAdapter: ChatAdapter

    private lateinit var layoutManager: LinearLayoutManager

    private lateinit var messageInfoList: MutableList<MessageInfo>

    // 录音相关
    private var animationRes = 0
    private var res = 0
    private lateinit var animationDrawable: AnimationDrawable
    private var animView: ImageView? = null

    // 其它功能 Fragment
    private val chatFunctionFragment: ChatFunctionFragment by lazy {
        ChatFunctionFragment()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_im_main)
        EventBus.getDefault().register(this)
        initWidget()
    }

    private fun initWidget() {

        fragments = mutableListOf()

        fragments.add(chatFunctionFragment)

        viewPagerAdapter = CommonFragmentPagerAdapter(
            supportFragmentManager, fragments
        )

        viewpager.adapter = viewPagerAdapter
        viewpager.currentItem = 0


        mDetector = EmotionInputDetector.with(this)
            //表情、更多页面布局Layout
            .setEmotionView(emotion_layout)
            //表情和更多功能是一个 Fragment，因此放在了ViewPager里面
            .setViewPager(viewpager)
            //聊天信息列表
            .bindToContent(mChatList)
            // 输入框
            .bindToEditText(mTextEt)
            // 表情按钮绑定
//            .bindToEmotionButton(emotion_button)
            // add按钮绑定
            .bindToAddButton(mEmotionAddIv)
            // 发送按钮绑定
            .bindToSendButton(emotion_send)
            // 录音按钮绑定
            .bindToVoiceButton(emotion_voice)
            // 显示“按下说话，放开发送”的 TextView 绑定
            .bindToVoiceText(mVoiceTextEt)
            .build()

        chatAdapter = ChatAdapter(this)
        layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.VERTICAL
        mChatList.setLayoutManager(layoutManager)
        mChatList.adapter = chatAdapter

        // 取消聊天列表中滚动条显示
        mChatList.isVerticalScrollBarEnabled = false
        mChatList.isHorizontalScrollBarEnabled = false

        mChatList.setOnScrollListener(object : RecyclerView.OnScrollListener() {
            @Override
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
//                super.onScrollStateChanged(recyclerView, newState)
                when (newState) {
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        chatAdapter.handler.removeCallbacksAndMessages(null)
                        chatAdapter.notifyDataSetChanged()
                    }
                    RecyclerView.SCROLL_STATE_DRAGGING -> {
                        chatAdapter.handler.removeCallbacksAndMessages(null)
                        mDetector.hideEmotionLayout(false)
                        mDetector.hideSoftInput()
                    }
                }
            }
        })

        chatAdapter.addItemClickListener(itemClickListener)


        loadData()
    }

    /**
     * item点击事件
     */
    private val itemClickListener = object : ChatAdapter.OnItemClickListener {
        override fun onHeaderClick(position: Int) {
            Toast.makeText(this@ImMainActivity, "onHeaderClick", Toast.LENGTH_SHORT).show()
        }

        override fun onImageClick(view: View, position: Int) {
            val location = IntArray(2)
            view.getLocationOnScreen(location)
            val fullImageInfo = FullImageInfo()
            fullImageInfo.locationX = location[0]
            fullImageInfo.locationY = location[1]
            fullImageInfo.width = view.width
            fullImageInfo.height = view.height
            fullImageInfo.imageUrl = messageInfoList[position].imageUrl
            EventBus.getDefault().postSticky(fullImageInfo)
            startActivity(Intent(this@ImMainActivity, FullImageActivity::class.java))
            overridePendingTransition(0, 0)
        }

        override fun onVoiceClick(imageView: ImageView, position: Int) {
            animView?.let {
                it.setImageResource(res)
            }

            val messageInfo = messageInfoList[position]
            when (messageInfo.type) {
                1 -> {
                    animationRes = R.drawable.voice_left
                    res = R.mipmap.icon_voice_left3
                }
                2 -> {
                    animationRes = R.drawable.voice_right
                    res = R.mipmap.icon_voice_right3
                }
            }
            animView = imageView
            animView!!.setImageResource(animationRes)
            animationDrawable = imageView.drawable as AnimationDrawable
            animationDrawable.start()
            MediaManager.playSound(messageInfo.filepath!!,
                MediaPlayer.OnCompletionListener {
                    animView!!.setImageResource(res)
                }
            )
        }
    }


    /**
     * 构造聊天数据
     */
    private fun loadData() {
        messageInfoList = mutableListOf()


        val messageInfo = MessageInfo()
        messageInfo.content = "你好，欢迎使用Rance的聊天界面框架"
        messageInfo.type = IMConstants.CHAT_ITEM_TYPE_LEFT
        messageInfo.header = "http://tupian.enterdesk.com/2014/mxy/11/2/1/12.jpg"
        messageInfo.time = "2019-04-22 10:10:10"
        messageInfoList.add(messageInfo)

        val messageInfo1 = MessageInfo()
        messageInfo1.filepath = "http://www.trueme.net/bb_midi/welcome.wav"
        messageInfo1.voiceTime = 3000
        messageInfo1.type = IMConstants.CHAT_ITEM_TYPE_RIGHT
        messageInfo1.sendState = IMConstants.CHAT_ITEM_SEND_SUCCESS
        messageInfo.time = "2019-04-22 10:12:10"
        messageInfo1.header = "http://img.dongqiudi.com/uploads/avatar/2014/10/20/8MCTb0WBFG_thumb_1413805282863.jpg"
        messageInfoList.add(messageInfo1)

        val messageInfo2 = MessageInfo()
        messageInfo2.imageUrl = "http://img4.imgtn.bdimg.com/it/u=1800788429,176707229&fm=21&gp=0.jpg"
        messageInfo2.type = IMConstants.CHAT_ITEM_TYPE_LEFT
        messageInfo.time = "2019-04-22 10:15:10"
        messageInfo2.header = "http://tupian.enterdesk.com/2014/mxy/11/2/1/12.jpg"
        messageInfoList.add(messageInfo2)

        chatAdapter.addAll(messageInfoList)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun messageEventBus(messageInfo: MessageInfo) {
        messageInfo.header = "http://img.dongqiudi.com/uploads/avatar/2014/10/20/8MCTb0WBFG_thumb_1413805282863.jpg"
        messageInfo.type = IMConstants.CHAT_ITEM_TYPE_RIGHT
        messageInfo.sendState = IMConstants.CHAT_ITEM_SENDING
        messageInfo.time = DateUtils.getNow("yyyy-MM-dd HH:mm:ss")
        messageInfoList.add(messageInfo)
        chatAdapter.add(messageInfo)
        mChatList.scrollToPosition(chatAdapter.count - 1)
        Handler().postDelayed(
            {
                messageInfo.sendState = IMConstants.CHAT_ITEM_SEND_SUCCESS
                chatAdapter.notifyDataSetChanged()
            }, 2000L
        )
        Handler().postDelayed({
            val messageInfo = MessageInfo()
            messageInfo.content = "这一条是模拟回复消息"
            messageInfo.type = IMConstants.CHAT_ITEM_TYPE_LEFT
            messageInfo.header = "http://tupian.enterdesk.com/2014/mxy/11/2/1/12.jpg"
            messageInfoList.add(messageInfo)
            chatAdapter.add(messageInfo)
            mChatList.scrollToPosition(chatAdapter.count - 1)
//            chatAdapter.notifyDataSetChanged()
        }, 3000)
    }

    override fun onBackPressed() {
        if (!mDetector.interceptBackPress()) {
            super.onBackPressed()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().removeStickyEvent(this)
        EventBus.getDefault().unregister(this)
    }
}
